package com.lire.shop.filter;

import com.lire.shop.dao.SessionLoginRepository;
import com.lire.shop.data.Constants;
import com.lire.shop.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Base64;
import java.util.Objects;
import java.util.Optional;

//@Component
//@Order(1)
public class AuthFilter implements Filter {
    @Autowired
    private SessionLoginRepository sessionLoginRepository;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        User curUser = (User) request.getSession().getAttribute(Constants.CURRENT_USER);
        if (Objects.isNull(curUser)) {
            User user = new User();
            user.setUsername("lire-1");
            user.setPassword("password-1");
            request.setAttribute(Constants.CURRENT_USER, user);
        }
        doFilter(servletRequest, servletResponse, filterChain);
//        User user = (User) request.getSession().getAttribute("user");
//        if (Objects.isNull(user)) {
//            request.getRequestDispatcher("/login").forward(servletRequest, servletResponse);
//            return;
//        }
//
//        SessionLogin sessionLogin = sessionLoginRepository.findByUsername(user.getUsername());
//        Long limitTime = sessionLogin.getLimitTime();
//        if (Instant.now().isAfter(Instant.ofEpochMilli(limitTime))) {
//            request.getRequestDispatcher("/login").forward(servletRequest, servletResponse);
//            return;
//        }

    }

    @Override
    public void destroy() {

    }
}
